#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2009-2016 Stephan Raue (stephan@openelec.tv)
# Copyright (C) 2016-present Team LibreELEC (https://libreelec.tv)
# Copyright (C) 2018-present Team CoreELEC (https://coreelec.org)

unset _CACHE_PACKAGE_LOCAL _CACHE_PACKAGE_GLOBAL _DEBUG_DEPENDS_LIST _DEBUG_PACKAGE_LIST

. config/options ""
. config/show_config

show_config
save_build_config

setup_toolchain target

$SCRIPTS/checkdeps
$SCRIPTS/build toolchain
$SCRIPTS/build squashfs:host
$SCRIPTS/build dosfstools:host
$SCRIPTS/build fakeroot:host
$SCRIPTS/build kmod:host
$SCRIPTS/build mtools:host
$SCRIPTS/build populatefs:host

if [ -n "$CUSTOM_GIT_HASH" ]; then
  GIT_HASH="$CUSTOM_GIT_HASH"
else
  GIT_HASH=$(git rev-parse HEAD)
fi

if [ "$LIBREELEC_VERSION" = "devel" ]; then
  GIT_ABBREV=${GIT_HASH:0:7}
  DEVEL_VERSION=$LIBREELEC_VERSION
  case "$BUILD_PERIODIC" in
    nightly) LIBREELEC_VERSION=nightly-$(date +%Y%m%d)-$GIT_ABBREV;;
    daily)   LIBREELEC_VERSION=daily-$(date +%Y%j)-$GIT_ABBREV;;
    weekly)  LIBREELEC_VERSION=weekly-$(date +%G%V)-$GIT_ABBREV;;
    monthly) LIBREELEC_VERSION=monthly-$(date +%Y%m)-$GIT_ABBREV;;
    *)       LIBREELEC_VERSION=devel-$(date +%s);;
  esac
fi

# Get origin url, fix git:// and git@github.com: urls if necessary
ORIGIN_URL="$(git remote -v | awk '$1 == "origin" { print $2 }' | head -1 | sed 's#\.git$##;s#^git:#https:#;s#^git@github\.com:#https://github.com/#')"

[ "${BUILDER_NAME,,}" = "official" ] && BUILDER_NAME=
if [ "$OFFICIAL" = "yes" ]; then
  LIBREELEC_BUILD="official"
else
  if [ -n "$BUILDER_NAME" ]; then
    LIBREELEC_BUILD="$BUILDER_NAME"
  else
    LIBREELEC_BUILD="community"
  fi
fi

if [ -n "$CUSTOM_VERSION" ]; then
  LIBREELEC_VERSION="$CUSTOM_VERSION"
fi

LIBREELEC_ARCH="${DEVICE:-$PROJECT}.$TARGET_ARCH"
TARGET_VERSION="$LIBREELEC_ARCH-$LIBREELEC_VERSION"

if [ -n "$CUSTOM_IMAGE_NAME" ]; then
  IMAGE_NAME="$CUSTOM_IMAGE_NAME"
else
  if [ "$DEVEL_VERSION" = "devel" ]; then
    IMAGE_NAME="$DISTRONAME-$LIBREELEC_ARCH-$OS_VERSION-$LIBREELEC_VERSION"
  else
    IMAGE_NAME="$DISTRONAME-$TARGET_VERSION"
  fi

  if [ -n "$UBOOT_SYSTEM" ] && [ "$UBOOT_SYSTEM" != "${DEVICE:-$PROJECT}" ]; then
    IMAGE_NAME="$IMAGE_NAME-$UBOOT_SYSTEM"
  fi
fi

if [ -n "$IMAGE_SUFFIX" ]; then
  IMAGE_NAME="$IMAGE_NAME-$IMAGE_SUFFIX"
fi

echo "$IMAGE_NAME" > $BUILD/BUILD_FILENAME

# setup fakeroot
rm -rf $FAKEROOT_SCRIPT   # remove $FAKEROOT_SCRIPT if it exist
touch $FAKEROOT_SCRIPT    # create an empty $FAKEROOT_SCRIPT
chmod +x $FAKEROOT_SCRIPT # make $FAKEROOT_SCRIPT executable
echo "chown -R 0:0 $INSTALL" >> $FAKEROOT_SCRIPT

# clean old install dirs
rm -rf $INSTALL
rm -rf $STAMPS_INSTALL
mkdir -p $INSTALL

# create baselayout
for directory in etc dev proc run sys tmp usr var flash storage; do
  mkdir -p $INSTALL/$directory
done
ln -sf /var/media $INSTALL/media
ln -sf /usr/lib $INSTALL/lib
ln -sf /usr/bin $INSTALL/bin
ln -sf /usr/sbin $INSTALL/sbin

if [ "$TARGET_ARCH" = "x86_64" ]; then
  ln -s /usr/lib $INSTALL/lib64
  ln -s /usr/lib $INSTALL/usr/lib64
fi

echo "$TARGET_VERSION" > $INSTALL/etc/release

# create /etc/os-release
echo -e "NAME=\"$DISTRONAME\"" > $INSTALL/etc/os-release
echo -e "VERSION=\"$LIBREELEC_VERSION\"" >> $INSTALL/etc/os-release
echo -e "ID=\"coreelec\"" >> $INSTALL/etc/os-release
echo -e "VERSION_ID=\"$OS_VERSION\"" >> $INSTALL/etc/os-release
echo -e "PRETTY_NAME=\"$DISTRONAME ($LIBREELEC_BUILD): $LIBREELEC_VERSION\"" >> $INSTALL/etc/os-release
echo -e "HOME_URL=\"https://coreelec.org\"" >> $INSTALL/etc/os-release
echo -e "BUG_REPORT_URL=\"$ORIGIN_URL\"" >> $INSTALL/etc/os-release
echo -e "BUILD_ID=\"$GIT_HASH\"" >> $INSTALL/etc/os-release
echo -e "COREELEC_ARCH=\"$LIBREELEC_ARCH\"" >> $INSTALL/etc/os-release
echo -e "COREELEC_BUILD=\"$LIBREELEC_BUILD\"" >> $INSTALL/etc/os-release
echo -e "COREELEC_PROJECT=\"$PROJECT\"" >> $INSTALL/etc/os-release
[ -n "$DEVICE" ] && echo -e "COREELEC_DEVICE=\"$DEVICE\"" >> $INSTALL/etc/os-release
[ -n "$BUILDER_NAME" ] && echo -e "BUILDER_NAME=\"$BUILDER_NAME\"" >> $INSTALL/etc/os-release
[ -n "$BUILDER_VERSION" ] && echo -e "BUILDER_VERSION=\"$BUILDER_VERSION\"" >> $INSTALL/etc/os-release

# create /etc/issue
echo "$GREETING0" >  $INSTALL/etc/issue
echo "$GREETING1" >> $INSTALL/etc/issue
echo "$GREETING2" >> $INSTALL/etc/issue
echo "$GREETING3" >> $INSTALL/etc/issue
echo "$GREETING4" >> $INSTALL/etc/issue
echo "$DISTRONAME ($LIBREELEC_BUILD): $LIBREELEC_VERSION ($LIBREELEC_ARCH)" >> $INSTALL/etc/issue

ln -sf /etc/issue $INSTALL/etc/motd

# populate base system...
$SCRIPTS/install libc
$SCRIPTS/install gcc

$SCRIPTS/install linux
export _CACHED_KERNEL_MODULE_DIR="$(get_module_dir)"

$SCRIPTS/install linux-drivers
$SCRIPTS/install linux-firmware
$SCRIPTS/install $BOOTLOADER
$SCRIPTS/install busybox
$SCRIPTS/install util-linux
$SCRIPTS/install corefonts
$SCRIPTS/install network

# Graphic support
[ ! "$DISPLAYSERVER" = "no" ] && $SCRIPTS/install $DISPLAYSERVER

# Multimedia support
[ ! "$MEDIACENTER" = "no" ] && $SCRIPTS/install mediacenter

# Sound support
[ "$ALSA_SUPPORT" = "yes" ] && $SCRIPTS/install alsa

# Automounter support
[ "$UDEVIL" = "yes" ] && $SCRIPTS/install udevil

# EXFAT support
[ "$EXFAT" = "yes" ] && $SCRIPTS/install fuse-exfat

# NTFS 3G support
[ "$NTFS3G" = "yes" ] && $SCRIPTS/install ntfs-3g_ntfsprogs

# Remote support
[ "$REMOTE_SUPPORT" = "yes" ] && $SCRIPTS/install remote

# Entware support
if [ "$ENTWARE_SUPPORT" = "yes" ]; then
  ln -sf /storage/.opt $INSTALL/opt
  $SCRIPTS/install entware
fi

# Install miscellaneous packages
$SCRIPTS/install misc-packages

# Virtual image creation support
[ "$PROJECT" = "Generic" ] && $SCRIPTS/install virtual

# Installer support
[ "$INSTALLER_SUPPORT" = "yes" ] && $SCRIPTS/install installer

# Devtools... (not for Release)
[ "$TESTING" = "yes" ] && $SCRIPTS/install testing

# Install gdb in all builds, including releases
$SCRIPTS/install debug

# OEM packages
[ "$OEM_SUPPORT" = "yes" ] && $SCRIPTS/install oem

# copy PROJECT related files to filesystem
if [ -d "$PROJECT_DIR/$PROJECT/filesystem" ]; then
  cp -PR $PROJECT_DIR/$PROJECT/filesystem/* $INSTALL
  # install project specific systemd services
  for service in $PROJECT_DIR/$PROJECT/filesystem/usr/lib/systemd/system/*.service; do
    if [ -f "$service" ]; then
      enable_service $(basename $service)
    fi
  done
fi

# copy DEVICE related files to filesystem
if [ -n "$DEVICE" -a -d "$PROJECT_DIR/$PROJECT/devices/$DEVICE/filesystem" ]; then
  cp -PR $PROJECT_DIR/$PROJECT/devices/$DEVICE/filesystem/* $INSTALL
  # install device specific systemd services
  for service in $PROJECT_DIR/$PROJECT/devices/$DEVICE/filesystem/usr/lib/systemd/system/*.service; do
    if [ -f "$service" ]; then
      enable_service $(basename $service)
    fi
  done
fi

# run depmod for base overlay modules
MODVER=$(basename $(ls -d $INSTALL/usr/lib/kernel-overlays/base/lib/modules/*))
find $INSTALL/usr/lib/kernel-overlays/base/lib/modules/$MODVER/ -name *.ko | \
  sed -e "s,$INSTALL/usr/lib/kernel-overlays/base/lib/modules/$MODVER/,," \
    > $INSTALL/usr/lib/kernel-overlays/base/lib/modules/$MODVER/modules.order
$TOOLCHAIN/bin/depmod -b $INSTALL/usr/lib/kernel-overlays/base -a -e -F "$BUILD/linux-$(kernel_version)/System.map" $MODVER

# strip kernel modules
for MOD in $(find $INSTALL/usr/lib/kernel-overlays/ -type f -name *.ko); do
  ${TARGET_KERNEL_PREFIX}strip --strip-debug $MOD
done

# symlink overlayed modules to /usr/lib/modules
ln -sT /var/lib/modules $INSTALL/usr/lib/modules

# symlink overlayed firmware to /usr/lib/firmware
ln -sT /var/lib/firmware $INSTALL/usr/lib/firmware

# make target dir
mkdir -p $TARGET_IMG
rm -rf $TARGET_IMG/$IMAGE_NAME.kernel

# copy kernel to target dir
cp -PR $BUILD/linux-$(kernel_version)/arch/$TARGET_KERNEL_ARCH/boot/$KERNEL_TARGET $TARGET_IMG/$IMAGE_NAME.kernel
chmod 0644 $TARGET_IMG/$IMAGE_NAME.kernel

# Set mksquashfs options for each compression method
if [ -z "$SQUASHFS_COMPRESSION_OPTION" ]; then
  if [ "${SQUASHFS_COMPRESSION:-gzip}" = "gzip" ]; then
    SQUASHFS_COMPRESSION_OPTION="-Xcompression-level 9 -b 262144"
  elif [ "$SQUASHFS_COMPRESSION" = "lzo" ]; then
    SQUASHFS_COMPRESSION_OPTION="-Xcompression-level 9 -b 524288"
  elif [ "$SQUASHFS_COMPRESSION" = "zstd" ]; then
    SQUASHFS_COMPRESSION_OPTION="-Xcompression-level 22 -b 262144"
  fi
fi

# create squashfs file, default to gzip if no compression configured
echo "rm -rf \"$TARGET_IMG/$IMAGE_NAME.system\"" >> $FAKEROOT_SCRIPT
echo "$TOOLCHAIN/bin/mksquashfs \"$BUILD/image/system\" \"$TARGET_IMG/$IMAGE_NAME.system\" -noappend -comp ${SQUASHFS_COMPRESSION:-gzip} ${SQUASHFS_COMPRESSION_OPTION}" >> $FAKEROOT_SCRIPT

# run fakeroot
$TOOLCHAIN/bin/fakeroot -- $FAKEROOT_SCRIPT
rm -rf $FAKEROOT_SCRIPT

# set permissions
chmod 0644 $TARGET_IMG/$IMAGE_NAME.system

if [ "$1" = "release" -o "$1" = "mkimage" -o "$1" = "amlpkg" -o "$1" = "noobs" ]; then

  RELEASE_DIR="target/$IMAGE_NAME"

  # cleanup
  rm -rf $RELEASE_DIR

  # create release dir
  mkdir -p $RELEASE_DIR

  # remove n previous created release image
  rm -rf $TARGET_IMG/$IMAGE_NAME.img.gz

  if [ -n "$BOOTLOADER" ]; then

    BOOTLOADER_DIR="$(get_pkg_directory "$BOOTLOADER")"

    if [ -d $BOOTLOADER_DIR/files ]; then
      cp -R $BOOTLOADER_DIR/files/* $RELEASE_DIR
    fi

    if find_file_path bootloader/release $BOOTLOADER_DIR/release; then
      echo "Running $FOUND_PATH"
      . $FOUND_PATH
    fi
  fi

  cp $ROOT/README* $RELEASE_DIR
  cp $ROOT/CHANGELOG* $RELEASE_DIR
  echo "$TARGET_VERSION" > $RELEASE_DIR/RELEASE

  if [ ! "$MEDIACENTER" = "no" ]; then
    echo "Kodi commit: $(get_pkg_version $MEDIACENTER)" >> $RELEASE_DIR/RELEASE
  fi

  mkdir -p $RELEASE_DIR/licenses
  cp $ROOT/licenses/* $RELEASE_DIR/licenses

  mkdir -p $RELEASE_DIR/target
  cp $TARGET_IMG/$IMAGE_NAME.system $RELEASE_DIR/target/SYSTEM
  cp $TARGET_IMG/$IMAGE_NAME.kernel $RELEASE_DIR/target/KERNEL

  # create md5sum's
  ( cd $RELEASE_DIR;
    md5sum -t target/SYSTEM > target/SYSTEM.md5;
    md5sum -t target/KERNEL > target/KERNEL.md5;
  )

  # create target directory
  mkdir -p $TARGET_IMG

  # remove an previous created release tarball
  rm -rf $TARGET_IMG/$IMAGE_NAME.tar

  # create release tarball
  tar cf $TARGET_IMG/$IMAGE_NAME.tar -C target $IMAGE_NAME

  # create sha256 checksum of tarball
  ( cd $TARGET_IMG
    sha256sum ${IMAGE_NAME}.tar > ${IMAGE_NAME}.tar.sha256
  )

  # create image files if requested
  if [[ ( "$1" = "amlpkg" || "$1" = "noobs" || "$1" = "mkimage" ) && -n "$BOOTLOADER" ]]; then
    # INSTALL_SRC_DIR can be board specific
    if [ -n "$DEVICE" -a -d "$PROJECT_DIR/$PROJECT/devices/$DEVICE/install" ]; then
      INSTALL_SRC_DIR="$PROJECT_DIR/$PROJECT/devices/$DEVICE/install"
    else
      INSTALL_SRC_DIR="$PROJECT_DIR/$PROJECT/install"
    fi

    if [ -n "$SUBDEVICES" ]; then
      [ "$PROJECT" = "Amlogic" ] && SUBDEVICES+=" Generic"
      for SUBDEVICE in $SUBDEVICES;do
        # variables used in image script must be passed
        env \
          PATH="$PATH:/sbin" \
          ROOT="$ROOT" \
          SCRIPTS="$SCRIPTS" \
          TOOLCHAIN="$TOOLCHAIN" \
          PROJECT_DIR="$PROJECT_DIR" \
          PROJECT="$PROJECT" \
          DEVICE="$DEVICE" \
          DISTRO="$DISTRO" \
          TARGET_IMG="$TARGET_IMG" \
          IMAGE_NAME="$IMAGE_NAME" \
          INSTALL_SRC_DIR="$INSTALL_SRC_DIR" \
          BOOTLOADER="$BOOTLOADER" \
          KERNEL_NAME="$KERNEL_NAME" \
          TARGET_KERNEL_ARCH="$TARGET_KERNEL_ARCH" \
          RELEASE_DIR=$RELEASE_DIR \
          UUID_STORAGE="$(uuidgen)" \
          DISTRO_BOOTLABEL="$DISTRO_BOOTLABEL" \
          DISTRO_DISKLABEL="$DISTRO_DISKLABEL" \
          UBOOT_SYSTEM="$UBOOT_SYSTEM" \
          UBOOT_VERSION="$UBOOT_VERSION" \
          EXTRA_CMDLINE="$EXTRA_CMDLINE" \
          SYSTEM_SIZE="$SYSTEM_SIZE" \
          SYSTEM_PART_START="$SYSTEM_PART_START" \
          OVA_SIZE="$OVA_SIZE" \
          SUBDEVICE=$SUBDEVICE \
          $SCRIPTS/mkimage
      done
    else
      # variables used in image script must be passed
      env \
        PATH="$PATH:/sbin" \
        ROOT="$ROOT" \
        SCRIPTS="$SCRIPTS" \
        TOOLCHAIN="$TOOLCHAIN" \
        PROJECT_DIR="$PROJECT_DIR" \
        PROJECT="$PROJECT" \
        DEVICE="$DEVICE" \
        DISTRO="$DISTRO" \
        TARGET_IMG="$TARGET_IMG" \
        IMAGE_NAME="$IMAGE_NAME" \
        INSTALL_SRC_DIR="$INSTALL_SRC_DIR" \
        BOOTLOADER="$BOOTLOADER" \
        KERNEL_NAME="$KERNEL_NAME" \
        TARGET_KERNEL_ARCH="$TARGET_KERNEL_ARCH" \
        RELEASE_DIR=$RELEASE_DIR \
        UUID_STORAGE="$(uuidgen)" \
        DISTRO_BOOTLABEL="$DISTRO_BOOTLABEL" \
        DISTRO_DISKLABEL="$DISTRO_DISKLABEL" \
        UBOOT_SYSTEM="$UBOOT_SYSTEM" \
        UBOOT_VERSION="$UBOOT_VERSION" \
        EXTRA_CMDLINE="$EXTRA_CMDLINE" \
        SYSTEM_SIZE="$SYSTEM_SIZE" \
        SYSTEM_PART_START="$SYSTEM_PART_START" \
        OVA_SIZE="$OVA_SIZE" \
        $SCRIPTS/mkimage
    fi
  fi

  # cleanup release dir
  rm -rf $RELEASE_DIR

  # create WeTek Play (Amlogic) ZIP update and auto-install packages if requested
  if [ "$1" = "amlpkg" ]; then
    echo "Creating Amlogic ZIP update package"

    AML_PKG_DIR="$RELEASE_DIR/ampl-pkg"

    # create package directory
    mkdir -p "$AML_PKG_DIR"

    # copy system and kernel images
    mkdir -p "$AML_PKG_DIR/system"
    cp $TARGET_IMG/$IMAGE_NAME.system $AML_PKG_DIR/system/SYSTEM
    cp $TARGET_IMG/$IMAGE_NAME.kernel $AML_PKG_DIR/KERNEL

    # copy update-binary and updater-script
    META_INF_DIR="$AML_PKG_DIR/META-INF/com/google/android"
    mkdir -p "$META_INF_DIR"
    cp $INSTALL_SRC_DIR/update-binary $META_INF_DIR
    cp $INSTALL_SRC_DIR/updater-script $META_INF_DIR

    # copy other files if any
    if [ -d "$INSTALL_SRC_DIR/files" ]; then
      cp -PR $INSTALL_SRC_DIR/files/* $AML_PKG_DIR
    fi

    # copy device tree image if any
    if [ -f "$INSTALL/usr/share/bootloader/dtb.img" ]; then
      cp "$INSTALL/usr/share/bootloader/dtb.img" $AML_PKG_DIR/dtb.img
    fi

    # create the update package
    pushd "$AML_PKG_DIR" > /dev/null
    zip -rq update.zip *

    # sign the update package
    echo "Signing the update package"
    mkdir -p sign
    SIGNAPK_DIR="$ROOT/tools/signapk"
    java -Xmx1024m -jar $SIGNAPK_DIR/signapk.jar -w $SIGNAPK_DIR/testkey.x509.pem $SIGNAPK_DIR/testkey.pk8 update.zip sign/$IMAGE_NAME-update.zip

    # create the auto-install package
    echo "Creating Amlogic ZIP auto-install package"
    pushd sign > /dev/null
    echo --update_package=/sdcard/$IMAGE_NAME-update.zip > factory_update_param.aml
    echo --wipe_data >> factory_update_param.aml
    echo --wipe_cache >> factory_update_param.aml
    if [ -f "$INSTALL_SRC_DIR/files/recovery.img" ]; then
      cp $INSTALL_SRC_DIR/files/recovery.img .
    fi

    if [ -f $INSTALL_SRC_DIR/files/aml_autoscript ]; then
      cp $INSTALL_SRC_DIR/files/aml_autoscript .
    fi

    # copy device tree image if any
    if [ -f "$INSTALL/usr/share/bootloader/dtb.img" ]; then
      cp "$INSTALL/usr/share/bootloader/dtb.img" .
    fi

    zip -q $TARGET_IMG/$IMAGE_NAME.zip *

    # create sha256 checksum of zip
    ( cd $TARGET_IMG
      sha256sum ${IMAGE_NAME}.zip > ${IMAGE_NAME}.zip.sha256
    )

    popd > /dev/null
    popd > /dev/null

  elif [ "$1" = "noobs" ]; then
    echo "Creating \"$1\" release tarball..."

    RELEASE_DIR="$TARGET_IMG/${IMAGE_NAME}-$1"

    # eg. LibreELEC_RPi, LibreELEC_RPi2 etc.
    NOOBS_DISTRO="${DISTRONAME}_${DEVICE:-$PROJECT}"

    # create release dir
    mkdir -p $RELEASE_DIR/${NOOBS_DISTRO}

    if [ -f $DISTRO_DIR/$DISTRO/${DISTRONAME}_40x40.png ]; then
      cp -PR $DISTRO_DIR/$DISTRO/${DISTRONAME}_40x40.png $RELEASE_DIR/${NOOBS_DISTRO}/${NOOBS_DISTRO}.png
    else
      cp -PR $DISTRO_DIR/$DISTRO/${DISTRONAME}.png $RELEASE_DIR/${NOOBS_DISTRO}/${NOOBS_DISTRO}.png
    fi
    cp -PR $ROOT/config/noobs/os.json $RELEASE_DIR/${NOOBS_DISTRO}
    cp -PR $ROOT/config/noobs/partition_setup.sh $RELEASE_DIR/${NOOBS_DISTRO}
    cp -PR $ROOT/config/noobs/partitions.json $RELEASE_DIR/${NOOBS_DISTRO}
    if [ -d $DISTRO_DIR/$DISTRO/noobs/marketing ]; then
      tar cf $RELEASE_DIR/${NOOBS_DISTRO}/marketing.tar -C $DISTRO_DIR/$DISTRO/noobs/marketing .
    else
      tar cf $RELEASE_DIR/${NOOBS_DISTRO}/marketing.tar -C $ROOT/config/noobs/marketing .
    fi
    cp $ROOT/README* $RELEASE_DIR/${NOOBS_DISTRO}
    cp $ROOT/CHANGELOG $RELEASE_DIR/${NOOBS_DISTRO}/release_notes.txt

    sed -e "s%@DISTRONAME@%$DISTRONAME%g" \
        -e "s%@PROJECT@%${DEVICE:-$PROJECT}%g" \
        -e "s%@LIBREELEC_VERSION@%$LIBREELEC_VERSION%g" \
        -e "s%@RELEASE_DATE@%$(date +%F)%g" \
        -e "s%@KERNEL_VERSION@%$(kernel_version)%g" \
        -e "s%@DESCRIPTION@%$DESCRIPTION%g" \
        -e "s%@ROOT_PASSWORD@%$ROOT_PASSWORD%g" \
        -e "s%@NOOBS_SUPPORTED_MODELS@%$NOOBS_SUPPORTED_MODELS%g" \
        -e "s%@NOOBS_HEX@%$NOOBS_HEX%g" \
        -i $RELEASE_DIR/${NOOBS_DISTRO}/os.json

    sed -e "s%@DISTRONAME@%$DISTRONAME%g" \
        -e "s%@PROJECT@%${DEVICE:-$PROJECT}%g" \
        -e "s%@SYSTEM_SIZE@%$SYSTEM_SIZE%g" \
        -i $RELEASE_DIR/${NOOBS_DISTRO}/partitions.json

    # create System dir
    mkdir -p $RELEASE_DIR/${NOOBS_DISTRO}/System

    BOOTLOADER_DIR="$(get_pkg_directory "$BOOTLOADER")"
    if [ -d $BOOTLOADER_DIR/files/3rdparty/bootloader/ ]; then
      cp -PR $BOOTLOADER_DIR/files/3rdparty/bootloader/* $RELEASE_DIR/${NOOBS_DISTRO}/System
    fi

    # copy Bootloader
    cp -PR $BUILD/bcm2835-bootloader-*/LICENCE* $RELEASE_DIR/${NOOBS_DISTRO}/System/
    cp -PR $BUILD/bcm2835-bootloader-*/bootcode.bin $RELEASE_DIR/${NOOBS_DISTRO}/System/
    cp -PR $BUILD/bcm2835-bootloader-*/fixup_x.dat $RELEASE_DIR/${NOOBS_DISTRO}/System/fixup.dat
    cp -PR $BUILD/bcm2835-bootloader-*/start_x.elf $RELEASE_DIR/${NOOBS_DISTRO}/System/start.elf
    [ -f $BUILD/bcm2835-bootloader-*/dt-blob.bin ] && cp -PR $BUILD/bcm2835-bootloader-*/dt-blob.bin $RELEASE_DIR/${NOOBS_DISTRO}/System/dt-blob.bin

    # copy system files
    cp $TARGET_IMG/$IMAGE_NAME.system $RELEASE_DIR/${NOOBS_DISTRO}/System/SYSTEM
    cp $TARGET_IMG/$IMAGE_NAME.kernel $RELEASE_DIR/${NOOBS_DISTRO}/System/kernel.img

    for dtb in $INSTALL/usr/share/bootloader/*.dtb; do
      if [ -f $dtb ]; then
        cp -PR $dtb $RELEASE_DIR/${NOOBS_DISTRO}/System
      fi
    done

    for overlay in $INSTALL/usr/share/bootloader/overlays/*; do
      if [ -f $overlay ]; then
        mkdir -p $RELEASE_DIR/${NOOBS_DISTRO}/System/overlays
        cp -PR $overlay $RELEASE_DIR/${NOOBS_DISTRO}/System/overlays
      fi
    done

    # create md5sum's
    ( cd $RELEASE_DIR/${NOOBS_DISTRO}/System;
      md5sum -t SYSTEM > SYSTEM.md5;
      md5sum -t kernel.img > kernel.img.md5;
    )

    # copy additional files
    mkdir -p $RELEASE_DIR/${NOOBS_DISTRO}/System/licenses
    cp $ROOT/licenses/* $RELEASE_DIR/${NOOBS_DISTRO}/System/licenses

    # create Storage dir
    mkdir -p $RELEASE_DIR/${NOOBS_DISTRO}/Storage

    # remove any previously created release tarball
    rm -rf $RELEASE_DIR/${NOOBS_DISTRO}/System.tar.xz
    rm -rf $RELEASE_DIR/${NOOBS_DISTRO}/Storage.tar.xz

    # create filesystem tarballs
    tar cJf $RELEASE_DIR/${NOOBS_DISTRO}/System.tar.xz -C $RELEASE_DIR/${NOOBS_DISTRO}/System/ .
    tar cJf $RELEASE_DIR/${NOOBS_DISTRO}/Storage.tar.xz -C $RELEASE_DIR/${NOOBS_DISTRO}/Storage/ .

    # remove filesystem dirs
    rm -rf $RELEASE_DIR/${NOOBS_DISTRO}/System
    rm -rf $RELEASE_DIR/${NOOBS_DISTRO}/Storage

    # remove any previously created release tarball
    rm -rf $TARGET_IMG/${IMAGE_NAME}-$1.tar

    # create release tarball
    tar cf $TARGET_IMG/${IMAGE_NAME}-$1.tar -C $TARGET_IMG ${IMAGE_NAME}-$1

    # create sha256 checksum of tarball
    ( cd $TARGET_IMG
      sha256sum ${IMAGE_NAME}-$1.tar > ${IMAGE_NAME}-$1.tar.sha256
    )
  fi

  if [ -d $RELEASE_DIR ]; then
    # cleanup release dir
    rm -rf $RELEASE_DIR
  fi
fi
